package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.Cate;
import com.itheima.ydd.service.CateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ydd_cate")
public class CateController {

    @Autowired
    private CateService cateService;

    @GetMapping("/list")
    public ResultData list(String catename, Integer page, Integer limit) {
        //构造分页构造器
        IPage<Cate> pageInfo = new Page<>(page, limit);
        //构造条件构造器
        LambdaQueryWrapper<Cate> queryWrapper = new LambdaQueryWrapper<>();

        //添加模糊匹配条件
        queryWrapper.like(StringUtils.isNotEmpty(catename), Cate::getCatename, catename);

        //添加排序条件根据 sort_num 降序排列
        queryWrapper.orderByDesc(Cate::getSort_num);
        cateService.page(pageInfo, queryWrapper);

        return ResultData.ok(" ", PageResult.init(pageInfo.getTotal(), pageInfo.getSize(), pageInfo.getPages(), pageInfo.getRecords()));

    }

    @GetMapping("/rowInfo")
    public ResultData rowInfo(@RequestParam Integer id) {

        return ResultData.ok(" ", cateService.getById(id));

    }


    @PostMapping("/update")
    public ResultData update(@RequestBody Cate cate) {

        return ResultData.ok(" ", cateService.updateById(cate));

    }

    @GetMapping("/del")
    public ResultData del(@RequestParam Integer id) {

        return ResultData.ok(" ", cateService.removeById(id));

    }


    @PostMapping("/add")
    public ResultData add(@RequestBody Cate cate) {
        cate.setDefault_data("1");
        return ResultData.ok(" ", cateService.save(cate));

    }


    @GetMapping("/all")
    public ResultData all() {

        return ResultData.ok(" ", cateService.list());

    }
}
